package io.vector.study.uploader.service.impl;

import io.vector.study.uploader.service.IUploadHandler;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.Comparator;

/**
 * Created by vector on 2017/5/24.
 */
@Service
public class UploadHandler implements IUploadHandler {

    private String UPLOAD_PATH = "C:\\Users\\vector\\Desktop\\upload";

    @Override
    public String saveFile(MultipartFile multipartFile) {
        String storeFileName = calcStoreFileName(multipartFile.getOriginalFilename());
        storeFile(multipartFile, new File(UPLOAD_PATH, storeFileName));
        return storeFileName;
    }

    @Override
    public String saveFileChunk(String fileId, MultipartFile multipartFile, int chunks, int chunk) {
        String storeFileName = calcStoreFileName(multipartFile.getOriginalFilename(), chunks, chunk);
        String chunkFolder = UPLOAD_PATH + "/" + fileId;
        storeFile(multipartFile, new File(chunkFolder, storeFileName));
        return storeFileName;
    }

    @Override
    public String mergeFileChunks(String fileId) {
        File chunkFolder = new File(UPLOAD_PATH, fileId);
        if (!chunkFolder.exists() || !chunkFolder.isDirectory()) {
            throw new RuntimeException("chunk file not found");
        }

        File[] fileChunks = chunkFolder.listFiles();
        if (ArrayUtils.isEmpty(fileChunks)) {
            throw new RuntimeException("chunk file not found");
        }

        Arrays.sort(fileChunks, Comparator.naturalOrder());
        String storeFileName = parseFileName(fileChunks[0].getName());
        File storeFile = new File(UPLOAD_PATH, storeFileName);
        try {
            FileOutputStream storeFileOutputStream = FileUtils.openOutputStream(storeFile, true);
            for (File fileChunk : fileChunks) {
                FileUtils.copyFile(fileChunk, storeFileOutputStream);
            }
            storeFileOutputStream.close();
            FileUtils.forceDelete(chunkFolder);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return storeFileName;
    }

    @Override
    public File getFile(String fileId) {
        return null;
    }

}
